package com.sky.service.impl;


import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.entity.AddressBook;
import com.sky.exception.BaseException;
import com.sky.mapper.AddressBookMapper;
import com.sky.result.Result;
import com.sky.service.IAddressBookService;
import com.sky.utils.UserThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 地址簿 服务实现类
 * </p>
 *
 * @author xieminghui
 * @since 2023-11-28
 */
@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {


    /**
     * 1查询当前用户所有地址
     *
     * @author: XieMingHui
     * @param: []
     * @return: com.sky.result.Result<java.util.List < com.sky.entity.AddressBook>>
     **/
    @Override
    public Result<List<AddressBook>> findList() {
        // 获取当前用户
        Long userId = UserThreadUtil.getThread().getId();
        // 查询对应用户id字段的所有地址
        List<AddressBook> addressList = lambdaQuery().eq(AddressBook::getUserId, userId)
                .list();
        return Result.success(addressList);
    }

    /**
     * 2新增地址
     *
     * @author: XieMingHui
     * @param: []
     * @return: 返回成功响应
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> saveAddress(AddressBook addressBook) {
        // 获取当前用户
        Long userId = UserThreadUtil.getThread().getId();
        Boolean isDefault = addressBook.getIsDefault();
        if (BooleanUtil.isTrue(isDefault)) {
            log.info("当前地址设置为默认地址,修改旧的默认地址");
            // 如果当前新增地址设置了默认,修改表中旧的默认地址字段
            boolean Result = lambdaUpdate().eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, 1)
                    .set(AddressBook::getIsDefault, 0)
                    .update();
            if (!Result) {
                throw new BaseException("默认地址修改失败");
            }
        }
        addressBook.setUserId(userId);
        // 新增地址
        if (save(addressBook)) {
            return Result.success("新增成功");
        }
        throw new BaseException("新增失败");
    }

    /**
     * 3.4.查询id地址或者默认地址
     *
     * @author: XieMingHui
     * @param: []
     * @return: 返回地址对象
     **/
    @Override
    public Result<AddressBook> findOneAddress(Long id) {
        // 获取当前用户
        Long userId = UserThreadUtil.getThread().getId();
        if (id == null) {
            log.info("没有传递地址id,则是查询默认地址");
            AddressBook addressBook = lambdaQuery().eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, true)
                    .one();
            return Result.success(addressBook);
        }
        log.info("根据地址id查询地址");
        AddressBook addressBook = getById(id);
        return Result.success(addressBook);
    }

    /**
     * 5根据id修改地址
     *
     * @author: XieMingHui
     * @param: [地址对象]
     * @return: 返回成功响应
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateAddress(AddressBook addressBook) {
        Long userId = UserThreadUtil.getThread().getId();
        Boolean isDefault = addressBook.getIsDefault();
        if (BooleanUtil.isTrue(isDefault)) {
            // 修改旧的默认地址为非默认
            updateDefult(userId);
        }
        addressBook.setUserId(userId);
        // 修改地址
        addressBook.setIsDefault(true);
        if (updateById(addressBook)) {
            return Result.success("修改成功");
        }
        throw new BaseException("修改失败");
    }

    /**
     * 6根据地址id删除地址
     *
     * @author: XieMingHui
     * @param: [地址id]
     * @return: 返回成功响应
     **/
    @Override
    public Result<String> deleteAddress(Long id) {
        boolean remove = removeById(id);
        if (remove) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }


    /**
     * 7设置默认地址
     *
     * @author: XieMingHui
     * @param: []
     * @return: 返回成功响应
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateDefaultAddress(AddressBook addressBook) {
        Long userId = UserThreadUtil.getThread().getId();
        // 修改旧的默认地址为非默认
        updateDefult(userId);
        addressBook.setUserId(userId);
        // 修改当前地址默认字段
        addressBook.setIsDefault(true);
        boolean defaultSettingResult = updateById(addressBook);
        if (defaultSettingResult){
            return  Result.success("默认地址修改成功");
        }
        throw new BaseException("默认地址修改失败");
    }
    // 修改旧的默认地址为非默认
    private void updateDefult(Long userId) {
        // 查询有没有默认地址
        Integer count = lambdaQuery().eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, true).count();
        log.info("查询到的默认地址结果,{}",count);
        if (count!=null) {
            // 已经有默认地址,修改表中旧的默认地址字段
            log.info("修改旧的默认地址为非默认");
            boolean updateResult = lambdaUpdate().set(AddressBook::getIsDefault, false)
                    .eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, true).update();
            if (!updateResult) {
                throw new BaseException("默认地址修改失败");
            }
        }
    }
}
